package cn.hdu.community.controller;

import cn.hdu.community.dto.Result;
import cn.hdu.community.entity.User;
import cn.hdu.community.mapper.UserMapper;
import cn.hdu.community.service.FileService;
import cn.hdu.community.service.RedisService;
import cn.hdu.community.service.UserService;
import cn.hdu.community.util.JwtTokenUtil;
import com.github.houbb.sensitive.word.core.SensitiveWordHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.sql.Date;
import java.util.Objects;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author zhangxin
 * @since 2022-04-01
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;

    @Autowired
    RedisService redisService;

    @Autowired
    UserMapper userMapper;

    @Autowired
    HttpServletRequest request;

    @Autowired
    FileService fileService;

    /**
     * 登录接口
     *
     * @param response
     * @param userEmail
     * @param userPassword
     * @param isRememberMe
     * @return
     */
    @RequestMapping("/login")
    public Result login(HttpServletResponse response, @RequestParam("userEmail") String userEmail, @RequestParam("userPassword") String userPassword, @RequestParam("isRememberMe") Boolean isRememberMe) {
        if (!userService.existsUserByEmail(userEmail)) {
            return Result.error("用户不存在", null);
        }
        User user = userService.findUserByEmail(userEmail);
        if (user.getUserPassword().equals(userPassword)) {
            //生成Token
            String token = JwtTokenUtil.createToken(user.getUserId(), isRememberMe, "user");
            //将Token放在头部返回给客户端
            response.setHeader(JwtTokenUtil.TOKEN_HEADER, JwtTokenUtil.TOKEN_PREFIX + token);
            return Result.success("登录成功", null);
        } else {
            return Result.error("密码错误", null);
        }
    }

    /**
     * 注册接口
     *
     * @param userEmail
     * @param userPassword
     * @param checkCode
     * @return
     */
    @RequestMapping("/registered")
    public Result registered(@RequestParam("userEmail") String userEmail, @RequestParam("userPassword") String userPassword, @RequestParam("checkCode") String checkCode) {
        String check_Code = (String) redisService.get("checkCode" + userEmail);
        if (checkCode.equals(check_Code)) {
            if (userService.existsUserByEmail(userEmail)) {
                return Result.error("用户已存在", null);
            }
            if (userService.insertUser(userEmail, userPassword)) {
                return Result.success("注册成功", null);
            } else {
                return Result.error("注册失败，请重试", null);
            }
        } else {
            return Result.error("验证码错误", null);
        }

    }

    /**
     * 获取用户全部信息
     *
     * @return
     */
    @RequestMapping("/getUserInfo")
    public Result getUserInfo() {
        return Result.success("获取成功", userService.getById((Serializable) request.getAttribute("userId")));
    }

    /**
     * 设置用户信息
     *
     * @param userInfo
     * @return
     */
    @RequestMapping("/setUserInfo")
    public Result setUserInfo(@RequestBody User userInfo) {
        User user = userService.getById((Serializable) request.getAttribute("userId"));
        String msg = "修改成功";
        //设置、更新用户个性签名
        user.setUserSignature(userInfo.getUserSignature());
        //设置、更新用户生日
        user.setUserBirthday(userInfo.getUserBirthday());
        //设置、更新用户职业
        user.setUserProfession(userInfo.getUserProfession());
        //设置、更新用户性别
        user.setUserGender(userInfo.getUserGender());
        //设置、更新用户用户名
        //API接口，查看是否有关键词，有返回true
        boolean contains = SensitiveWordHelper.contains(userInfo.getUserName());
        if (contains) {
            msg = "用户名违规";
        } else {
            user.setUserName(userInfo.getUserName());
        }
        userService.updateById(user);
        if (msg.equals("用户名违规")) {
            return Result.error(msg, null);
        }
        return Result.success(msg, null);
    }

    /**
     * 设置用户头像
     *
     * @param file
     * @return
     */
    @RequestMapping("/setUserAvatar")
    public Result setUserAvatar(MultipartFile file) {
        User user = userService.getById((Serializable) request.getAttribute("userId"));
        if (fileService.checkImgFileSiz(file).getCode() == 404) {
            return fileService.checkImgFileSiz(file);
        }
        Result result = fileService.uploadImgFile(file);
        if (result.getCode() == 200) {
            user.setUserAvatar((String) result.getData());
            userMapper.updateById(user);
            return Result.success("设置成功", null);
        } else {
            return Result.internalError(500);
        }

    }

    /**
     * 修改用户密码
     *
     * @param oldPassword
     * @param newPassword
     * @return
     */
    @RequestMapping("/changePassword")
    public Result changePassword(@RequestParam("oldPassword") String oldPassword, @RequestParam("newPassword") String newPassword) {
        User user = userService.getById((Serializable) request.getAttribute("userId"));
        if (!user.getUserPassword().equals(oldPassword)) {
            return Result.error("原密码错误", null);
        }
        user.setUserPassword(newPassword);
        if (userService.updateById(user)) {
            return Result.success("修改成功", null);
        } else {
            return Result.internalError(null);
        }
    }

    /**
     * 用户注销
     *
     * @param userPassword
     * @return
     */
    @RequestMapping("/logout")
    public Result deleteUser(@RequestParam("userPassword") String userPassword) {
        User user = userService.getById((Serializable) request.getAttribute("userId"));
        if (user.getUserPassword().equals(userPassword)) {
            if (userService.removeById(user))
                return Result.success("注销成功", null);
            else
                return Result.internalError(null);
        } else {
            return Result.error("密码错误", null);
        }
    }
}
